package com.oedtech.esl.service.SNService;

import com.alibaba.fastjson.JSONObject;
import com.oedtech.esl.model.SNModel.UpdateResult;
import com.oedtech.esl.model.esl.EslImg;
import com.oedtech.esl.model.esl.EslImgPage;
import com.oedtech.esl.model.esl.EslTab;
import com.oedtech.esl.repository.esl.EslImgDao;
import com.oedtech.esl.repository.esl.EslTabDao;
import com.oedtech.esl.utils.HttpUtils;
import com.oedtech.esl.utils.ImageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.stream.FileImageInputStream;
import javax.transaction.Transactional;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * @Author QiuLongYu
 * @Date 2019/7/29
 */
@Service
public class InterfacesService {

    private final static Logger LOG = LoggerFactory.getLogger(InterfacesService.class);

    @Autowired
    private EslImgDao eslImgDao;
    @Autowired
    private EslTabDao eslTabDao;
    final Base64.Decoder decoder = Base64.getDecoder();

    /**
     * 图片接收并处理
     * @param storeCode 门店编码
     * @param tinyIP   价签ID
     * @param jo       入参Json数据
     * @return
     * @throws IOException
     */
    @Transactional
    public String imgManager(String storeCode, String tinyIP, JSONObject jo) throws IOException {
        String sid=jo.getString("sid");
        String back_url = jo.getString("back_url");
        String name = jo.getString("name");
        Integer default_page_id = jo.getInteger("default_page_id");

        int num=eslTabDao.updateEsl(sid, back_url, name, default_page_id, tinyIP,storeCode);
        if(num==0){
            return "价签id不存在:"+tinyIP;
        }
        EslTab eslTab=eslTabDao.findById(tinyIP).orElse(null);
        String str=jo.getJSONArray("pages").toJSONString();
        List<EslImgPage>list=JSONObject.parseArray(str, EslImgPage.class);
        for (EslImgPage eslImgPage : list) {

            String imgPath="sn_img_file/"+storeCode+"/"+tinyIP+"-"+eslImgPage.getId();
            String binPath="sn_img_bin/"+storeCode+"/"+tinyIP+"-"+eslImgPage.getId()+".bin";

           byte[]img=decoder.decode(eslImgPage.getImage());
            ImageUtils.imgTobin(eslTab.getEslFirmware(),binPath,img);
            eslImgDao.insertOrUpdateImg(tinyIP, imgPath, eslImgPage.getName(), eslImgPage.getId(),binPath);
            FileOutputStream fos=null;
                File file = new File(imgPath);
                if(!file.getParentFile().exists()){
                    file.getParentFile().mkdir();
                }
               fos=new FileOutputStream(file);
                fos.write(eslImgPage.getImage().getBytes("utf8"));
                fos.close();
//                return null;

        }
        return null;
    }

    /**
     * 异步上报价签刷新结果
     * @param tinyIP 价签id
     * @param statusNo  刷新成功OR失败
     */
    @Transactional
    public void sendUpdateResult(String tinyIP,String statusNo,String errmsg){
        EslTab eslTab=eslTabDao.findById(tinyIP).orElse(null);

        JSONObject jo = new JSONObject();
        jo.put("status_no",0);
        jo.put("user", eslTab.getStoreCode());
        jo.put("type","ESL_UPDATE_ACK");
        UpdateResult updateResult = new UpdateResult();
        updateResult.setEsl_id(eslTab.getTinyIP());
        updateResult.setAp_id(eslTab.getNetworkIP());
        updateResult.setSid(eslTab.getSid());
        long time=System.currentTimeMillis()-eslTab.getEslStatus().getLastUpdateTime().getTime();
        if("1000".equals(statusNo)&&time>=60*60*1000){
            updateResult.setStatus_no("1001");
            updateResult.setErrmsg("价签离线");
        }else {
            updateResult.setStatus_no(statusNo);
            updateResult.setErrmsg(errmsg);
        }

        int n = eslTab.getDefaultPageId();
        for (EslImg eslImg : eslTab.getEslImgList()) {
            if (eslImg.getPage() == n) {
                String str=getFileString(eslImg.getImgPath());
                updateResult.setEsl_image(str);
                break;
            }
        }
        List<UpdateResult> list = new ArrayList<>();
        list.add(updateResult);
        jo.put("data",list);
//        LOG.info("sendUpdateResult:[{}]",jo.toJSONString());
        String result=HttpUtils.sendPost(eslTab.getBackUrl(), jo.toJSONString());

        LOG.info(result);
    }

    private String getFileString(String address){
        File file = new File(address);
        FileInputStream fis=null;
        try {
            byte[]b=new byte[(int)file.length()];
            fis=new FileInputStream(file);
            fis.read(b);
            return new String(b);
        }  catch (IOException e) {
            LOG.error("",e);
            return null;
        }finally {
            if(fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    LOG.error("",e);
                }
            }
        }
    }
}
